package org.hashdb.client.net.bio;

import com.fasterxml.jackson.core.JsonParser;
import org.hashdb.client.net.bio.get.*;
import org.hashdb.client.net.bio.msg.Message;
import org.hashdb.client.net.bio.send.ActHeartbeatMessage;
import org.hashdb.client.net.bio.send.AuthenticationMessage;
import org.hashdb.client.net.bio.send.CloseMessage;
import org.hashdb.client.net.bio.send.CommandMessage;
import org.hashdb.client.util.JsonService;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Date: 2023/12/1 2:10
 *
 * @author huanyuMake-pecdle
 * @version 0.0.1
 */
public enum MessageType {
    HEARTBEAT(HeartbeatMessage.class),
    ACT_HEARTBEAT(ActHeartbeatMessage.class),
    AUTH(AuthenticationMessage.class),
    ACT_AUTH(ActAuthenticationMessage.class),
    DATA_CHUNK(DataChunkMessage.class),
    CLOSE(CloseMessage.class),
    ERROR(ErrorMessage.class),
    COMMAND(CommandMessage.class),
    ACK_COMMAND(ActCommandMessage.class);

    private Class<? extends Message> messageClass;

    private static Map<Class<? extends Message>, MessageType> messageTypeMap;

    MessageType(Class<? extends Message> messageClass) {
        registerMessageClass(messageClass, this);
    }

    private static synchronized void registerMessageClass(Class<? extends Message> messageClass, MessageType type) {
        if (messageTypeMap == null) {
            messageTypeMap = new HashMap<>();
        }
        messageTypeMap.put(messageClass, type);
        type.messageClass = messageClass;
    }

    public Message deserialize(JsonParser jp) throws IOException {
        return JsonService.parse(jp, messageClass);
    }

    public Class<? extends Message> getMessageClass() {
        return messageClass;
    }

    public static MessageType typeOf(Class<? extends Message> messageClass) {
        return messageTypeMap.get(messageClass);
    }
}
